/**
 * 类似于原生的setInterval函数，参数一致，不同的是不同的定时器需要手动new一个。
 * @param { function } callback 每次回调
 * @param { number } time 每次回调间隔时间
 * @returns { $clear } $clear函数用于清除定时器
 */
const Interval = function (callback, time) {
    this.start = new Date().getTime();
    this.end;
    this.offset;
    this.loopNum = 0;
    this.timeoutTag = null;
    this.time = time;
    this.callback = callback;
    this.$set(time);
}
Interval.prototype.$set = function (_time) {
    var that = this;
    if (this.timeoutTag === undefined) return;
    clearTimeout(this.timeoutTag);
    this.timeoutTag = null;
    that.timeoutTag = setTimeout(function () {
      that.loopNum++;
      that.end = new Date().getTime();
      that.callback();
      that.offset = that.end - that.start - that.time * that.loopNum;
      if (that.offset > 0) {
        that.$set(that.time - that.offset);
      } else if (that.offset < 0) {
        that.$set(that.time + that.offset);
      } else {
        that.$set(that.time);
      }
    }, _time);
}
Interval.prototype.$clear = function () {
    clearTimeout(this.timeoutTag);
    this.timeoutTag = undefined;
}

module.exports = Interval